<template>
  <div class="order-wrapper">
    <div
      v-if="
        resourceSet.includes('/web/data-statistic/bill-statistic/订单数据统计')
      "
      v-loading="datacardLoading"
      class="datacard-search-wrapper"
    >
      <div class="panel">
        <div class="panel-header">订单数据统计</div>
        <div class="form-wrapper">
          <div class="form-content">
            <i-form
              class="iform"
              :layoutSpan="layoutSpan"
              :labelWidth="labelWidth"
              :breakpoint="breakpoint"
              :inline="true"
              :items="queryFormItems"
              :form="queryForm"
              :rules="queryFormRules"
            >
              <template slot="date">
                <el-form-item prop="date">
                  <SearchDatePicker
                    type="month"
                    :start.sync="queryForm.startTime"
                    :end.sync="queryForm.endTime"
                    :disable-date="disableDate"
                  />
                </el-form-item>
              </template>
              <template slot="address">
                <el-form-item>
                  <HycAddressCascader
                    v-model="queryForm.area"
                    :level="0"
                    :clearable="true"
                    size="small"
                  />
                </el-form-item>
              </template>
              <template slot="merchant" v-if="queryForm.containSubMch">
                <el-form-item>
                  <SearchMerchants
                    v-model="queryForm.mchUserId"
                    :defaultOptions="false"
                    size="small"
                  />
                </el-form-item>
              </template>
            </i-form>
            <div class="btn-wrapper">
              <el-button type="primary" size="small" @click="initDataCard">
                查询
              </el-button>
              <el-button size="small" @click="reset">重置</el-button>
            </div>
          </div>
        </div>
      </div>
      <data-card
        :data="dataCard"
        :items="dataCardItems"
        :tips="tips"
        @handleChange="initDataCard"
      />
    </div>
    <EchartPanel
      v-loading="dayBillLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/bill-statistic/每日充电订单统计'
        )
      "
      :title="chargeDaily"
      :timeUnit="'date'"
      @handleTableData="handleChargeDaily"
      :echartsOption="chargeOption"
    />
    <EchartPanel
      v-loading="monthlyBillLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/bill-statistic/每月充电订单统计'
        )
      "
      :title="chargeMonthy"
      :timeUnit="'month'"
      @handleTableData="handleChargeMonthly"
      :echartsOption="chargeOption"
    />
    <EchartPanel
      v-loading="provinceBillLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/bill-statistic/各省订单走势图'
        )
      "
      :title="orderTrend"
      :defaultFormItems="['date', 'merchant', 'merchantCheckbox']"
      :timeUnit="'month'"
      @handleTableData="handleProvinceOrderAmount"
      :echartsOption="orderOption"
    />
    <EchartPanel
      v-loading="billRateLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/bill-statistic/订单比例图')
      "
      :title="orderRatio"
      :timeUnit="'month'"
      @handleTableData="handleOrderRatio"
      :echartsOption="orderRatioOption"
    />
    <EchartPanel
      v-loading="errorBillReasonLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/bill-statistic/异常订单原因')
      "
      class="error-order-reason"
      :title="errorOrderReason"
      :timeUnit="'month'"
      :tableData="tableData"
      @handleTableData="handleErrorBillTableData"
      :columns="abnormalOrderColumns"
    />
    <EchartPanel
      v-loading="errorBillAmountLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/bill-statistic/异常订单分布')
      "
      :title="errorOrderDistribution"
      :timeUnit="'month'"
      @handleTableData="handleMchErrorOrderAmount"
      :echartsOption="orderOption"
    />
  </div>
</template>
<script>
import dayjs from 'dayjs'
import HycAddressCascader from '@/components/hycAddressCascader'
import SearchMerchants from '@/components/SearchMerchants'
import EchartPanel from '@/components/EchartPanel'
import * as visualizationFun from '@/utils/visualizationFun'
import { constValue } from '@/config/echartsStyle'
import DataCard from './components/DataCard'
import {
  getTotalBillStatistic,
  getDailyBillStatistic,
  getMonthlyBillStatistic,
  getBillRatio,
  getMchErrorBillAmount,
  getProvinceBillStatistic,
  getErrorBillReason,
} from '@/api/statistics'
import { chargeOption, orderOption, orderRatioOption } from './data/order'
export default {
  name: 'StatisticsOrder',
  components: { HycAddressCascader, SearchMerchants, EchartPanel, DataCard },
  data() {
    return {
      layoutSpan: 24,
      labelWidth: 20,
      breakpoint: [
        [768, 1],
        [992, 2],
        [1200, 2],
        [1920, 3],
        [Infinity, 4],
      ],
      queryForm: {
        containSubMch: true,
        mchUserId: '',
        startTime: null,
        endTime: null,
        area: {},
      },
      queryFormItems: [
        {
          slot: 'date',
        },
        {
          slot: 'address',
        },
        {
          slot: 'merchant',
        },
      ],
      disableDate: {
        startTime: dayjs('2024-01-01').valueOf(),
        endTime: dayjs().endOf('month').valueOf(),
      },
      queryFormRules: {
        date: [
          {
            validator: (rule, value, callback) => {
              if (this.queryForm.startTime && !this.queryForm.endTime) {
                callback(new Error('请选择结束时间'))
                return false
              }
              if (!this.queryForm.startTime && this.queryForm.endTime) {
                callback(new Error('请选择开始时间'))
                return false
              }
              callback()
            },
          },
        ],
      },
      datacardLoading: false,
      dayBillLoading: false,
      monthlyBillLoading: false,
      provinceBillLoading: false,
      billRateLoading: false,
      errorBillReasonLoading: false,
      errorBillAmountLoading: false,
      range: '',
      radioButtons: [
        {
          value: 6,
          label: '最近6月',
        },
        {
          value: 12,
          label: '最近12月',
        },
      ],
      tableData: {},
      chargeDaily: '每日充电订单统计',
      chargeMonthy: '每月充电订单统计',
      orderTrend: '各省订单走势图',
      orderRatio: '订单比例',
      errorOrderReason: '异常订单原因',
      errorOrderDistribution: '异常订单分布',
      tips: [
        '数据统计截止前一天',
        // '数据统计包含自营及下级代理订单',
        '总利润统计=临充总利润+时长卡总利润+服务费总利润',
        '临充总利润=临充消费-当前电费成本',
        '时长卡总利润=已售出时长卡流水-已售出时长卡电费成本',
        '服务费总利润=临充订单服务费+时长卡订单服务费',
        '总未支付订单=后付费模式未支付订单流水总额。',
        // '临充收费 = 当期余额消费 + 当期第三方消费 + 当期预支付已使用 - 服务费',
      ],
      dataCard: {
        totalIncome: 0,
        totalZeroIncome: 0,
        totalMonthlyCardIncome: 0,
        totalServiceIncome: 0,
        totalChargeCount: 0,
        totalUnPayedBillAmount: 0,
      },
      dataCardItems: [
        {
          label: '总利润统计',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalIncome).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
        {
          label: '临充总利润',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalZeroIncome).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
        {
          label: '时长卡总利润',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalMonthlyCardIncome).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
        // {
        //   label: '服务费总利润',
        //   symbol: '￥',
        //   unit: '元',
        //   formatter: (data) => {
        //     return Number(data.totalServiceIncome).toLocaleString('zh-CN', {
        //       maximumFractionDigits: 2,
        //     })
        //   },
        // },
        // {
        //   label: '和能量总收入',
        //   symbol: '￥',
        //   unit: '元',
        //   formatter: (data) => {
        //     return (
        //       data.totalAndEnergyIncome &&
        //       Number(data.totalAndEnergyIncome.toFixed(2)).toLocaleString()
        //     )
        //   },
        // },
        {
          label: '总未支付订单',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalUnPayedBillAmount).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
        {
          label: '充电订单总数',
          // symbol: '￥',
          // unit: '元',
          formatter: (data) => {
            return Number(data.totalChargeCount).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
      ],
      chargeOption: chargeOption,
      orderOption: orderOption,
      orderRatioOption: orderRatioOption,
      abnormalOrderFormItems: [
        {
          slot: 'address',
        },
        {
          type: 'text',
          value: 'mchUserId',
          placeholder: '请输入代理商',
          clearable: true,
        },
      ],
      abnormalOrderColumns: [
        {
          label: '原因',
          prop: 'reason',
        },
        {
          label: '订单数',
          prop: 'totalAmount',
        },
        {
          label: '占比',
          prop: 'percent',
          formatter: (data) => {
            return data.percent + '%'
          },
        },
      ],
    }
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
  },
  created() {
    this.initDataCard()
  },
  methods: {
    reset() {
      this.queryForm = {
        containSubMch: true,
        startTime: null,
        endTime: null,
        area: {},
        mchUserId: '',
      }
    },
    initDataCard() {
      this.datacardLoading = true
      const { containSubMch, mchUserId, startTime, endTime, area } =
        this.queryForm
      const params = {
        containSubMch,
        ...(mchUserId && { mchUserId }),
        ...(startTime && { startTime }),
        ...(endTime && { endTime }),
        ...(area && { province: area.province }),
      }
      getTotalBillStatistic(params).then(
        (res) => {
          this.datacardLoading = false
          this.dataCard = res
        },
        () => {
          this.datacardLoading = false
        }
      )
    },
    handleChargeDaily(params, instance) {
      this.dayBillLoading = true
      getDailyBillStatistic(params).then(
        (res) => {
          this.dayBillLoading = false
          let orderXAxis = []
          let chargeData = []
          let miniChargeSumData = []
          let cardChargeSumData = []
          let zfbMiniChargeSum = []
          res.forEach((item) => {
            orderXAxis.push(item.day)
            chargeData.push(item.billAmount)
            miniChargeSumData.push(item.weixinBillAmount)
            zfbMiniChargeSum.push(item.zfbBillAmount)
            cardChargeSumData.push(item.cardBillAmount)
          })
          visualizationFun.getXAxis(orderXAxis)
          let chargeMax = visualizationFun.getMax(chargeData)

          instance.setOption({
            animation: true,
            xAxis: {
              data: orderXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '每日充电订单统计（个）',
                max: chargeMax,
                nameTextStyle: {
                  padding: [100, 0, 0, 100],
                },
                interval: chargeMax / constValue.splitNumber,
              },
            ],
            series: [
              {
                data: chargeData,
              },
              {
                data: miniChargeSumData,
              },
              {
                data: zfbMiniChargeSum,
              },
              {
                data: cardChargeSumData,
              },
            ],
          })
        },
        () => {
          this.dayBillLoading = false
        }
      )
    },
    handleChargeMonthly(params, instance) {
      this.monthlyBillLoading = true
      getMonthlyBillStatistic(params).then(
        (res) => {
          this.monthlyBillLoading = false
          let orderXAxis = []
          let chargeData = []
          let miniChargeSumData = []
          let cardChargeSumData = []
          let zfbMiniChargeSum = []
          res.forEach((item) => {
            orderXAxis.push(item.month)
            chargeData.push(item.billAmount)
            miniChargeSumData.push(item.weixinBillAmount)
            zfbMiniChargeSum.push(item.zfbBillAmount)
            cardChargeSumData.push(item.cardBillAmount)
          })
          visualizationFun.getMonthXAxis(orderXAxis)
          let chargeMax = visualizationFun.getMax(chargeData)

          instance.setOption({
            animation: true,
            xAxis: {
              data: orderXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '每月充电订单统计（个）',
                max: chargeMax,
                nameTextStyle: {
                  padding: [100, 0, 0, 100],
                },
                interval: chargeMax / constValue.splitNumber,
              },
            ],
            series: [
              {
                data: chargeData,
              },
              {
                data: miniChargeSumData,
              },
              {
                data: zfbMiniChargeSum,
              },
              {
                data: cardChargeSumData,
              },
            ],
          })
        },
        () => {
          this.monthlyBillLoading = false
        }
      )
    },
    handleOrderRatio(params, instance) {
      this.billRateLoading = true
      getBillRatio(params).then(
        (res) => {
          this.billRateLoading = false
          instance.setOption({
            animation: true,
            series: {
              data: [
                { value: res.timecardBillAmount, name: '时长卡抵扣订单' },
                // { value: res.freeBillAmount, name: '免费订单' },
                { value: res.zeroBillAmount, name: '临充付费订单' },
                { value: res.errorBillAmount, name: '异常订单' },
              ],
            },
          })
        },
        () => {
          this.billRateLoading = false
        }
      )
    },
    handleProvinceOrderAmount(params, instance) {
      this.provinceBillLoading = true
      getProvinceBillStatistic(params).then(
        (res) => {
          this.provinceBillLoading = false
          let xAxis = []
          let orderAmount = []
          res.forEach((item) => {
            xAxis.push(item.provinceName)
            orderAmount.push(item.billAmount)
          })
          let orderAmountMax = visualizationFun.getMax(orderAmount)
          instance.setOption({
            xAxis: {
              data: xAxis,
              show: true,
              axisLabel: { interval: 0, rotate: 40 },
            },
            yAxis: [
              {
                name: '充电订单总量（次）',
                show: true,
                max: orderAmountMax,
                interval: orderAmountMax / constValue.splitNumber,
                nameTextStyle: {
                  padding: [100, 0, 0, 100],
                },
              },
            ],
            series: [
              {
                name: '充电订单总量（次）',
                type: 'bar',
                data: orderAmount,
              },
            ],
            animation: true,
          })
        },
        () => {
          this.provinceBillLoading = false
        }
      )
    },
    handleErrorBillTableData(params) {
      this.errorBillReasonLoading = true
      getErrorBillReason(params).then(
        (res) => {
          this.errorBillReasonLoading = false
          this.tableData = {
            list: res,
            totalCount: res.length,
          }
        },
        () => {
          this.errorBillReasonLoading = false
        }
      )
    },
    // reset() {},
    handleMchErrorOrderAmount(params, instance) {
      this.errorBillAmountLoading = true
      getMchErrorBillAmount(params).then(
        (res) => {
          this.errorBillAmountLoading = false
          let xAxis = []
          let errorOrderAmount = []
          res.forEach((item) => {
            xAxis.push(item.mchUserName)
            errorOrderAmount.push(item.errorBillAmount)
          })
          let errorOrderAmountMax = visualizationFun.getMax(errorOrderAmount)
          instance.setOption({
            xAxis: {
              data: xAxis,
              show: true,
              axisLabel: { interval: 0, rotate: 40 },
            },
            yAxis: [
              {
                name: '异常订单数量（次）',
                show: true,
                max: errorOrderAmountMax,
                nameTextStyle: {
                  padding: [100, 0, 0, 100],
                },
                interval: errorOrderAmountMax / constValue.splitNumber,
              },
            ],
            series: [
              {
                name: '异常订单数量（次）',
                type: 'bar',
                data: errorOrderAmount,
              },
            ],
            animation: true,
          })
        },
        () => {
          this.errorBillAmountLoading = false
        }
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.error-order-reason {
  display: flex;
  flex-direction: column;
  position: relative;
  ::v-deep .table-search-wrapper {
    order: 2;
  }
  &::v-deep .table-dash {
    padding: 0 24px 20px 20px !important;
    // max-width: 60%;
    // max-height: 450px;
  }
  &::v-deep .chart-container {
    order: 1;
    // position: absolute;
    height: auto;
    // right: 20%;
    // bottom: 420px;
    width: auto;
    .echart-panel-time_range {
      position: relative;
      left: 0;
      top: 0;
      padding-left: 25px;
      padding-top: 20px;
      & + div {
        padding: 0 !important;
      }
    }
  }
}

.datacard-search-wrapper {
  .form-wrapper {
    .form-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-left: -12px;
    }
    .iform {
      flex: 1;
      margin-left: 16px;
      margin-top: -5px;
    }
    .btn-wrapper {
      min-width: 130px;
      margin: 0 24px;
      .dash-control {
        cursor: pointer;
        margin: 0 5px;
        display: inline-block;
      }
    }
  }
  .data-card {
    margin: 40px 0 40px;
  }
}
</style>
